package commands

import (
	"bitwormhole.com/starter/cli"
	"bitwormhole.com/starter/cli/arguments"
	"github.com/bitwormhole/starter/markup"
	"github.com/bitwormhole/starter/vlog"
	"github.com/go-git/go-git/v5"
)

// GitCommit ...
type GitCommit struct {
	markup.Component `class:"cli-handler-registry"`
}

func (inst *GitCommit) _Impl() cli.HandlerRegistry {
	return inst
}

// GetHandlers ...
func (inst *GitCommit) GetHandlers() []*cli.HandlerRegistration {
	hr := &cli.HandlerRegistration{
		Name:    "go-git-commit",
		Handler: inst.handle,
		Help:    nil,
		OnInit:  nil,
	}
	return []*cli.HandlerRegistration{hr}
}

func (inst *GitCommit) handle(t *cli.Task) error {

	const (
		flagM = "-m"
	)

	atb := arguments.NewTemplateBuilder()
	atb.AcceptOption(flagM, 1)
	args := atb.Create().Parse(t.Arguments)

	msg := args.GetOption(flagM).Value(0).String()
	wd := t.WD
	opt := &git.CommitOptions{}

	return inst.commit(wd, msg, opt)
}

func (inst *GitCommit) commit(wd string, msg string, opt *git.CommitOptions) error {

	r, err := git.PlainOpenWithOptions(wd, &git.PlainOpenOptions{DetectDotGit: true})
	if err != nil {
		return err
	}

	wktree, err := r.Worktree()
	if err != nil {
		return err
	}

	id, err := wktree.Commit(msg, opt)
	if err != nil {
		return err
	}

	vlog.Info("git.commit.result:", id.String())
	return nil
}
